#!/usr/bin/python
# -*- coding: utf-8 -*-


import sys, getopt
import os
import wave



def convert(wavIn):
    if os.path.isfile(wavIn) == False:
        print("%s not exist" % wavIn)
        return

    name, fmt = wavIn.split(".", 1)
    if fmt != 'wav':
        print("input error not wav")
        return

    cFile = name + ".c"

    if os.path.isfile(cFile) == True:
        print("%s is exist, will cover it" % cFile)

    wavFd = wave.open(wavIn, 'rb')
    print("getnchannels %d" % wavFd.getnchannels())
    print("getsampwidth %d" % wavFd.getsampwidth())
    print("getframerate %d" % wavFd.getframerate())
    print("getnframes %d"  % wavFd.getnframes())
    print("getcomptype %s" % wavFd.getcomptype())
    print("getcompname %s" % wavFd.getcompname())
    print(wavFd.getparams())

    print(wavFd.readframes(1))
    print("tell %d total bytes %d" % (wavFd.tell(), wavFd.getnframes() * wavFd.getsampwidth() * wavFd.getnchannels()))
    wavFd.setpos(0)

    cFd = open(cFile, 'w')
    cFd.write("// totle array size: %d\r\n" % (wavFd.getnframes() * wavFd.getsampwidth() * wavFd.getnchannels()))
    cFd.write("const unsigned char speech_%s[] = {\r\n" % name)

    numPerLine = int(16 / wavFd.getsampwidth() / wavFd.getnchannels())
    totalFrames = wavFd.getnframes()

    while totalFrames:

        getFrames = min(totalFrames, numPerLine)

        arr = wavFd.readframes(getFrames)
        for val in arr:
            cFd.write("0x%02x, " % val)
        cFd.write("\r\n")

        totalFrames -= getFrames

    cFd.write("};\r\n")
    cFd.close()

    wavFd.close()

    print("generate %s success" % cFile)


if __name__ == "__main__":
    # print(sys.argv)
    convert(sys.argv[1])
